﻿#define _CRT_SECURE_NO_WARNINGS

#include "List.h"

//创建节点
LTNode* BuyNode(LTDateType x)
{
	LTNode* newNode = (LTNode*)malloc(sizeof(LTNode));
	if (newNode == NULL)
	{
		perror("BuyNode fail!");
		exit(1);
	}
	newNode->date = x;
	newNode->next = newNode->prav = newNode;
	return newNode;
}

//完成初始化
LTNode* LTInit()
{
	LTNode* newNode = BuyNode(-1);
	return newNode;
}

//实现展示链表
void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur->next != phead)
	{
		pcur = pcur->next;
		printf("%d->", pcur->date);
	}
	printf("NULL\n");
}

//实现尾插尾删
void LTPushBack(LTNode* phead, LTDateType x)
{
	assert(phead);
	LTNode* node = BuyNode(x);
	node->prav = phead->prav;
	node->next = phead;
	phead->prav->next = node;
	phead->prav = node;
}

void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* del = phead->prav;
	del->prav->next = phead;
	phead->prav = del->prav;
	free(del);
	del = NULL;
}

//实现头插头删
void LTPushFront(LTNode* phead, LTDateType x)
{
	assert(phead);
	LTNode* node = BuyNode(x);
	node->next = phead->next;
	node->prav = phead;
	phead->next->prav = node;
	phead->next = node;
}


void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* del = phead->next;
	phead->next = del->next;
	del->prav = phead;
	free(del);
	del = NULL;
}

//实现查找pos
LTNode* LTFind(LTNode* phead, LTDateType x)
{
	assert(phead && phead->next != phead);
	LTNode* pcur = phead;
	while (pcur->next != phead)
	{
		pcur = pcur->next;
		if (pcur->date == x)
		{
			return pcur;
		}
	}
	return NULL;
}

//实现在pos位置之后插⼊数据
void LTInsort(LTNode* pos, LTDateType x)
{
	assert(pos);
	LTNode* node = BuyNode(x);
	node->next = pos->next;
	node->prav = pos;
	pos->next->prav = node;
	pos->next = node;
}

//删除pos节点
void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* del = pos;
	del->next->prav = pos->prav;
	del->prav->next = del->next;
	free(del);
	del = NULL;
}

//实现销毁链表
void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* ret = pcur;
		pcur = pcur->next;
		free(ret);
		ret = NULL;
	}
}